﻿using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using System.Diagnostics;
using DE.Sdc.SharePoint.SPContentStructure.Common;

namespace DE.Sdc.SharePoint.SPContentStructure.Import
{
    [Serializable]
    [XmlType(AnonymousType = true, Namespace = DeploymentConstants.Namespace)]
    [XmlRoot(Namespace = DeploymentConstants.Namespace, IsNullable = false)]
    public class File : BaseFile<Folder>, IImportDefinition<SPFile, SPFolder>
    {
        private string _path;

        [XmlIgnore]
        public SPFile UpdatedSPObject { get; internal set; }

        [XmlAttribute]
        public override string Path
        {
            get
            {
                if (string.IsNullOrEmpty(_path) && Item.List != null)
                    return System.IO.Path.Combine(Item.List.Path, Item.Title);

                return _path;
            }
            set
            {
                _path = value;
            }
        }

        protected override bool IsNewVersion(object sharePointObject)
        {
            if (sharePointObject == null || Version == 0)
                return true;

            SPFile file = (SPFile)sharePointObject;
            Trace.WriteLine("Check version number for file '" + file.Url + "'", "ContentStructureImporter:ImportFile");

            if (file.Properties.ContainsKey(DeploymentConstants.ContentStructureVersion))
            {
                int currentVersion = (int)file.Properties[DeploymentConstants.ContentStructureVersion];
                Trace.WriteLine("Current version is " + currentVersion + ", new version is " + Version + " for item '" + file.Url + "'", "ContentStructureImporter:ImportFile");
                return Version > currentVersion;
            }

            return true;
        }

        protected override void SetNewVersion(object sharePointObject)
        {
            if (sharePointObject == null || Version == 0)
                return;

            SPFile file = (SPFile)sharePointObject;
            if (file.Properties.ContainsKey(DeploymentConstants.ContentStructureVersion))
                file.Properties[DeploymentConstants.ContentStructureVersion] = Version;
            else
                file.Properties.Add(DeploymentConstants.ContentStructureVersion, Version);
        }

        public virtual void ImportDefinition(SPFile file, SPFolder parentFolder)
        {
            ImportDefinition(file, parentFolder, true);
        }

        public virtual void ImportDefinition(SPFile file, SPFolder parentFolder, bool changeFileLevel)
        {
            if (Action == ActionType.AddOrUpdate && file == null || 
                Action == ActionType.Replace && IsNewVersion(file))
            {
                string itemPath = DeploymentHelper.Resolve(Path, parentFolder.ParentWeb.Locale);
                string filePath = itemPath;
                if (!DeploymentContext.Current.ExistsContentStructureZip())
                    filePath = GetFeatureRootedPath(itemPath);

                MemoryStream fileStream = null;
                try
                {
                    if (file != null && Action == ActionType.Replace)
                        Checkout(file);

                    fileStream = new MemoryStream(DeploymentHelper.ReadFile(filePath, Encoding.Default), false);
                    file = parentFolder.Files.Add(Item.Url ?? Item.Title, fileStream,
                                                  Action == ActionType.Replace);

                }
                finally
                {
                    if (fileStream != null)
                        fileStream.Close();
                }
            }

            SetNewVersion(file);

            if (changeFileLevel)
                ChangeFileLevel(file, Item);
            UpdatedSPObject = file;
        }
    }
}